package com.weijun.keepalive_daemon.utils

import android.content.Context
import android.media.AudioAttributes
import android.media.MediaPlayer
import com.weijun.keepalive_daemon.R
import com.weijun.keepalive_daemon.logE

/**
 * @author: weijun
 * date: 2023/7/6
 * description:
 */
internal object MediaPlayerUtil {

    private lateinit var player: MediaPlayer

    val isPlaying:Boolean
        get() {
            if (::player.isInitialized) {
                return player.isPlaying
            }
            return false
        }

    fun init(context: Context){
        stop()
        player = MediaPlayer.create(context, R.raw.no_notice).apply {
            setWakeMode(context.applicationContext, 1)
            setVolume(0f, 0f)
            setOnErrorListener { _, _, _ ->
                "播放出错".logE()
                false
            }
            setOnCompletionListener { it.start() }
            if (ROMUtils.isHuawei()) {
                setAudioAttributes(
                    AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_ASSISTANCE_ACCESSIBILITY).build()
                )
            }
            play()
        }
    }

    fun play(){
        if (::player.isInitialized && !player.isPlaying) {
            player.start()
        }
    }

    fun pause(){
        if (::player.isInitialized && player.isPlaying) {
            player.pause()
        }
    }

    fun stop(){
        if (::player.isInitialized) {
            try {
                player.apply {
                    stop()
                    release()
                }
            }catch (ignore:Exception) { }
        }
    }
}